//角色列表的Grid
var role_gird = Ext.create('Ext.grid.Panel', {
	header: false,
	store: Ext.data.StoreManager.lookup('roleListStore'),
	columns: [{
		text: '角色名称',
		dataIndex: 'chineseName',
		flex: 1
	}],
	selModel: roleListGirdCheckBox,
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: '添加角色',
			tooltip: '添加角色',
			icon: 'static/images/icons/fam/add.gif',
			listeners: {
				click: function() {
					addRoleWin.show();
				}
			}
		}, '-', {
			itemId: 'roleListDeleteButton',
			text: '删除角色',
			tooltip: '删除角色',
			disabled: true,
			icon: 'static/images/icons/fam/delete.gif',
			listeners: {
				click: function() {
					Ext.Msg.show({
						title: '提示',
						message: '你确认删除这些角色了吗?',
						buttons: Ext.Msg.YESNO,
						icon: Ext.Msg.QUESTION,
						fn: function(btn) {
							if(btn === 'yes') {
								var selectArray = role_gird.getSelectionModel().getSelected(); //得到被选择的行的数组.
								var jsonArray = new Array();
								Ext.each(selectArray.items, function(result) {
									jsonArray.push(result.data.id);
								});
								var json = Ext.JSON.encode(jsonArray);
								Ext.Ajax.request({
									url: zuulUrl+'/'+authServiceName+'/admin/role/del',
									async: true, //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
									method: 'post',
									params: {
										roleIdJson: json
										//_method:"DELETE"
									},
									success: function(response, opts) {
										Ext.Msg.alert("Success", "删除成功");
										Ext.data.StoreManager.lookup('roleListStore').reload();
									},
									failure: function(response, opts) {
										Ext.Msg.alert("Error", "该功能暂时不可用！");
									}
								});
							}
						}
					});
				}
			}
		}]

	}],
	listeners: {
		itemclick: function(grid, record, item, index, e, eOpts) {
			Ext.getCmp('authRoleCenter').removeAll(false); // 先移除原有的items,不然直接添加会叠加,如果设置为true就是会自动销毁之前的组件，之后就无法在使用这个组件了
			Ext.data.StoreManager.lookup('roleAuthStore').proxy.url = zuulUrl+'/'+authServiceName+'/admin/role/auth/'+ record.data.id;
			roleAuthGird.setStore(Ext.data.StoreManager.lookup('roleAuthStore'));
			Ext.data.StoreManager.lookup('roleAuthStore').reload();
			Ext.getCmp('authRoleCenter').add(roleAuthGird);
		}
	}
});

//角色权限列表
var roleAuthGird = Ext.create('Ext.grid.Panel', {
	header: false,
	store: Ext.data.StoreManager.lookup('roleAuthStore'),
	columns: [{
			text: '可访问资源',
			dataIndex: 'url',
			flex: 1,
			editor: {
				xtype: 'textfield',
				allowBlank: false
			}
		},
		{
			text: '资源描述',
			dataIndex: 'urlDetial',
			flex: 1,
			editor: {
				xtype: 'textfield',
				allowBlank: false
			}
		},{
			text: '是否仅读',
			dataIndex: 'readOnly',
			renderer:function(value){
				return value==1?'是':'否';
			}
		}
	],
	selModel: roleAuthGirdCheckBox,
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: '添加权限',
			tooltip: '添加权限',
			icon: 'static/images/icons/fam/add.gif',
			listeners: {
				click: function() {
					var roleId = role_gird.getSelectionModel().getSelected().items[0].data.id;
					Ext.data.StoreManager.lookup('roleAddAuthListStore').proxy.url = zuulUrl+'/'+authServiceName+'/admin/role/addAuth/'+ roleId;
					roleAddAuthGird.setStore(Ext.data.StoreManager.lookup('roleAddAuthListStore'));
					Ext.data.StoreManager.lookup('roleAddAuthListStore').reload();
					roleAddAuthWin.down('#roleAddAuthWinButton').setDisabled(true);
					roleAddAuthWin.show();
				}
			}
		}, '-', {
			itemId: 'roleAuthDeleteButton',
			text: '删除权限',
			tooltip: '删除权限',
			icon: 'static/images/icons/fam/delete.gif',
			disabled: true,
			listeners: {
				click: function() {
					var roleId = role_gird.getSelectionModel().getSelected().items[0].data.id;
					var selectArray = roleAuthGird.getSelectionModel().getSelected(); //得到被选择的行的数组.
					var jsonArray = new Array();
					Ext.each(selectArray.items, function(result) {
						jsonArray.push(result.data.id);
					});
					var json = Ext.JSON.encode(jsonArray);
					Ext.Ajax.request({
						url: zuulUrl+'/'+authServiceName+'/admin/role/auth/del',
						async: true, //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
						method: 'post',
						params: {
							delUrlJson: json,
							roleId:roleId
							//_method:"DELETE"
						},
						success: function(response, opts) {
							while(selectArray.length != 0) {
								Ext.data.StoreManager.lookup('roleAuthStore').remove(selectArray.items[0]);
							}
						},
						failure: function(response, opts) {
							Ext.Msg.alert("Error", "该功能暂时不可用！");
						}
					});
				}
			}
		}]
	}]
});

//用户管理Tab下的grid panel
var userList = Ext.create('Ext.grid.Panel', {
	store: Ext.data.StoreManager.lookup('userListStore'),
	columns: [{
		text: '用户名',
		dataIndex: 'username',
		flex: 1,
		filter: { //用于形成搜索框
			type: 'string',
			emptyText: '输入要搜索的用户名',
			serializer: function(filter) {
				return filter.value;
			}
		}
	}, {
		text: '姓名',
		dataIndex: 'realName',
		flex: 1,
		filter: { //用于形成搜索框
			type: 'string',
			emptyText: '输入要搜索的用户名',
			serializer: function(filter) {
				return filter.value;
			}
		}
	}],
	plugins: {
		gridfilters: true //启用filters
	},
	selModel: userListGridCheckBox,
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: '添加用户',
			tooltip: '添加用户',
			icon: 'static/images/icons/fam/add.gif',
			listeners: {
				click: function() {
					userWin.setTitle('添加用户');
					userBaseMsgForm.reset();//清空基本信息表格
					userBaseMsgForm.getForm().findField('password1').setConfig('allowBlank',false);//设置密码项为必填项
					userBaseMsgForm.getForm().findField('password2').setConfig('allowBlank',false);//设置密码项为必填项
					userBaseMsgForm.getForm().findField('password1').setConfig('emptyText','6至8位字符');//设置提示文本
					userBaseMsgForm.getForm().findField('password2').setConfig('emptyText','6至8位字符');//设置提示文本
					Ext.data.StoreManager.lookup('roleListStore').reload();
					userTabPanel.down('#userHasRolesList').setSelection();//将角色表的被选中状态清除
					userList.isCreate=1;//用于判断提交的时候是添加用户还是修改用户
					userWin.show();
				}
			}
		}, '-', {
			itemId: 'userListDeleteButton',
			text: '删除用户',
			tooltip: '删除用户',
			disabled: true,
			icon: 'static/images/icons/fam/delete.gif',
			listeners: {
				click: function() {
					var selectArray = userList.getSelectionModel().getSelected(); //得到被选择的行的数组
					var jsonArray = new Array();
					var object;
					Ext.each(selectArray.items, function(result) {
						object = new Object();
						object['id'] = result.data.id;
						jsonArray.push(object);
					});
					var json = Ext.JSON.encode(jsonArray);
					Ext.Ajax.request({
						url: zuulUrl+'/'+authServiceName+'/admin/user/del',
						method: 'post',
						params: {
							idJson: json
							//_method:"DELETE"
						},
						success: function(response, opts) {
							Ext.Msg.alert('成功', '删除成功！');
							Ext.each(jsonArray, function(result) {
								var record = Ext.data.StoreManager.lookup('userListStore').findRecord('id', result.id);
								Ext.data.StoreManager.lookup('userListStore').remove(record);
							});
						},
						failure: function(response, opts) {
							console.log('server-side failure with status code ' + response.status);
						}
					});
				}
			}
		}, '-', {
			text: '编辑用户',
			itemId: 'userListEditorButton',
			tooltip: '编辑用户',
			icon: 'static/images/icons/fam/plugin.gif',
			disabled: true,
			listeners: {
				click: function() {
					Ext.Ajax.request({
						url: zuulUrl+'/'+authServiceName+'/admin/user/roles/'+userList.getSelectionModel().getSelected().items[0].data.id,
						method: 'get',
						success: function(response, opts) {
							userBaseMsgForm.reset();//清空基本信息表格
							userTabPanel.setActiveTab(0);
							userTabPanel.down('#userHasRolesList').setSelection();
							userWin.setTitle('编辑用户');
							//将用户的用户名和姓名填充到表单上
							userBaseMsgForm.getForm().findField('username').setValue(userList.getSelectionModel().getSelected().items[0].data.username);
							userBaseMsgForm.getForm().findField('realName').setValue(userList.getSelectionModel().getSelected().items[0].data.realName);
							userBaseMsgForm.getForm().findField('password1').setConfig('allowBlank',true);//设置密码项为非必填项
							userBaseMsgForm.getForm().findField('password2').setConfig('allowBlank',true);//设置密码项为非必填项
							userBaseMsgForm.getForm().findField('password1').setConfig('emptyText','不填则代表不修改');//设置提示文本
							userBaseMsgForm.getForm().findField('password2').setConfig('emptyText','不填则代表不修改');//设置提示文本
							var roles = Ext.decode(response.responseText);
							var jsonArray = new Array();
							Ext.each(roles, function(role) {
								jsonArray.push(Ext.data.StoreManager.lookup('roleListStore').findRecord('id', role.id))
							});
							//将用户的角色设定为选中状态
							userTabPanel.down('#userHasRolesList').setSelection(jsonArray);
							userList.isCreate=0;//用于判断提交的时候是添加用户还是修改用户
							userWin.show();
						},
						failure: function(response, opts) {
							console.log('server-side failure with status code ' + response.status);
						}
					});

				}
			}
		}],
	}]
});

//权限管理Tab下的grid panel
var authList = Ext.create('Ext.grid.Panel', {
	store: Ext.data.StoreManager.lookup('authListStore'),
	columns: [{
			text: '被保护的请求路径',
			dataIndex: 'url',
			flex: 1,
			editor: {
				xtype: 'textfield',
				allowBlank: false
			}
		},
		{
			text: '路径描述',
			dataIndex: 'urlDetial',
			flex: 1,
			editor: {
				xtype: 'textfield',
				allowBlank: false
			}
		},{
			text: '是否仅读',
			dataIndex: 'readOnly',
			renderer:function(value){
				return value==1?'是':'否';
			},
			editor: {
				xtype: 'combo',
				editable: false,//防止用户直接在下拉框里输入
                store: Ext.data.StoreManager.lookup('urlReadOnlyStore'),
                queryMode: 'local',
                displayField: 'name',
                valueField: 'num',
                allowBlank: false//是否允许为空
			}
		}
	],
	selModel: authListCheckBox,
	plugins: {
		rowediting: {
			clicksToMoveEditor: 2,
			//autoCancel: false
			listeners:[{
				edit:function(editor, context, eOpts ){
					console.log(context);
					Ext.Ajax.request({
						url: zuulUrl+'/'+authServiceName+'/admin/url',
						method: 'put',
						params: {
							id: context.record.data.id,
							url:context.record.data.url,
							detail:context.record.data.urlDetial,
							readOnly:context.newValues.readOnly//不知道为什么这里只能用newValue里面的值
						},
						success: function(response, opts) {
							//如果是新添加权限则要将返回的urlId赋值到store中
							if(context.record.data.id==-1)
								Ext.data.StoreManager.lookup('authListStore').findRecord('id', context.record.data.id).set('id',response.responseText);
							Ext.data.StoreManager.lookup('authListStore').findRecord('id', context.record.data.id).set('readOnly',context.newValues.readOnly);
						},
						failure: function(response, opts) {
							console.log('server-side failure with status code ' + response.status);
						}
					});
				}
			}]
		}
	},
	dockedItems: [{
		xtype: 'toolbar',
		items: [{
			text: '添加权限',
			tooltip: '添加权限',
			icon: 'static/images/icons/fam/add.gif',
			listeners: {
				click: function() {
					var lastRecord = Ext.data.StoreManager.lookup('authListStore').getAt(Ext.data.StoreManager.lookup('authListStore').getCount() - 1);
					if((lastRecord == null) || (lastRecord.data.url != '' && lastRecord.data.urlDetial != '')) {
						var newRecord = {
							"id":Ext.create("MyApp.data.MyModelX").data.id.replace(/-/g, ""),
							"url": "",
							"urlDetial": ""
						};
						Ext.data.StoreManager.lookup('authListStore').add(newRecord);
					}
				}
			}
		}, '-', {
			itemId: 'authDeleteButton',
			text: '删除权限',
			tooltip: '删除权限',
			icon: 'static/images/icons/fam/delete.gif',
			disabled: true,
			listeners: {
				click: function() {
					var selectArray = authList.getSelectionModel().getSelected(); //得到被选择的行的数组.
					var jsonArray = new Array();
					Ext.each(selectArray.items, function(item){
						jsonArray.push(item.data.id);
					});
					var json = Ext.JSON.encode(jsonArray);
					Ext.Ajax.request({
						url: zuulUrl+'/'+authServiceName+'/admin/url/del',
						async: true, //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
						method: 'post',
						params: {
							urlJson:json
							//_method:"DELETE"
						},
						success: function(response, opts) {
							while(selectArray.items.length!=0){
								Ext.data.StoreManager.lookup('authListStore').remove(selectArray.items[0]);
							}
						},
						failure: function(response, opts) {
							Ext.Msg.alert("Error", "该功能暂时不可用！");
						}
					});
				}
			}
		}]
	}]
});

//显示角色可以添加的权限的列表
var roleAddAuthGird = Ext.create('Ext.grid.Panel', {
	header: false,
	store: Ext.data.StoreManager.lookup('roleAddAuthListStore'),
	columns: [{
			text: '权限路径',
			dataIndex: 'url',
			flex: 1,
		},
		{
			text: '权限描述',
			dataIndex: 'urlDetial',
			flex: 1,
		},{
			text: '是否仅读',
			dataIndex: 'readOnly',
			renderer:function(value){
				return value==1?'是':'否';
			}
		}
	],
	selModel: roleAddAuthGirdCheckBox
});